<?php

class NewsController extends BaseAdminController {

	public function actionView($id) {
		$this->render('view', array(
			'model' => $this->loadModel($id, 'News'),
		));
	}

	public function actionCreate() {
		$model = new News;
		if (isset($_POST['News'])) {
			$model->attributes = $_POST['News'];
			$model->created_by 	= Yii::app()->user->id;
			$model->modified_by = Yii::app()->user->id;
			if($_POST['News']['created']=='0000-00-00 00:00:00'){
				$model->created = date('Y-m-d H:i:s');
			}
			if($_POST['News']['modified']=='0000-00-00 00:00:00'){
				$model->modified = date('Y-m-d H:i:s');
			}
			$images_type = Yii::app()->params['photo']['types'];
			if ($model->save()) {
				$last_id = $model->getPrimaryKey();
				$Images = array();
				if(isset($_FILES) && count($_FILES)>0){
					foreach($_FILES as $key => $file){
						if(in_array($file['type'],$images_type)){
							if($file['error']==0){//check is change images
							switch ($file['type'])
								{
									case 'image/png':
										$ext = 'png';
										break;
									case 'image/gif':
										$ext = 'gif';
										break;
									default:
										$ext = 'jpg';
										break;
								}
								$image_name = Common::EncryptClientId($last_id).time().'_'.$key.'.'.$ext;
								$file_upload=CUploadedFile::getInstanceByName("$key");
								$dir = Yii::app()->params['media_path'].'/news/'.$key;
								if(is_dir($dir)==false) mkdir($dir);
								if($file_upload->saveAs($dir.'/'.$image_name)){
									$Images["$key"]["url"] = '/media/news/'.$key.'/'.$image_name;
									$Images["$key"]["ext"] = $ext;
								}
							}
						}
					}
				}
				//update images
				if(count($Images)>0){
					News::model()->updateByPk($last_id, array('images'=>serialize($Images)));
				}
				if (Yii::app()->request->isAjaxRequest)
					Yii::app()->end();
				else
					$this->redirect(array('view', 'id' => $model->id));
			}
		}

		$this->render('create', array( 'model' => $model));
	}

	public function actionUpdate($id) {
		$model = $this->loadModel($id, 'News');

		$images_type = Yii::app()->params['photo']['types'];
		if (isset($_POST['News'])) {
			$model->attributes = $_POST['News'];
			$model->modified_by = Yii::app()->user->id;
			if($_POST['News']['modified']=='0000-00-00 00:00:00'){
				$model->modified = date('Y-m-d H:i:s');
			}
			if ($model->save()) {
				$Images = ($model->images!='')?unserialize($model->images):array();
				if(isset($_FILES) && count($_FILES)>0){
					foreach($_FILES as $key => $file){
						if(in_array($file['type'],$images_type)){
							if($file['error']==0){//check is change images
								switch ($file['type'])
								{
									case 'image/png':
										$ext = 'png';
										break;
									case 'image/gif':
										$ext = 'gif';
										break;
									default:
										$ext = 'jpg';
										break;
								}
								$image_name = Common::EncryptClientId($id).time().'_'.$key.'.'.$ext;
								$file_upload=CUploadedFile::getInstanceByName("$key");
								$dir = Yii::app()->params['media_path'].'/news/'.$key;
								if(is_dir($dir)==false) mkdir($dir);
								@unlink(Yii::getPathOfAlias('rootPath').$Images["$key"]["url"]);
								if($file_upload->saveAs($dir.'/'.$image_name)){
									$Images["$key"]["url"] = '/media/news/'.$key.'/'.$image_name;
									$Images["$key"]["ext"] = $ext;
								}
							}
						}
					}
				}
				if(count($Images)>0){
					News::model()->updateByPk($id, array('images'=>serialize($Images)));
				}
				$this->redirect(array('view', 'id' => $model->id));
			}
		}

		$this->render('update', array(
				'model' => $model,
				));
	}

	public function actionDelete($id) {
		if (Yii::app()->request->isPostRequest) {
			$model = $this->loadModel($id, 'News');
			if($model->images!=''){
				$images = unserialize($model->images);
				if(count($images)>0){
					foreach ($images as $value){
						@unlink(Yii::getPathOfAlias('rootPath').$value['url']);
					}
				}
			}
			$model->delete();
			if (!Yii::app()->request->isAjaxRequest)
				$this->redirect(array('admin'));
		} else
			throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
	}
	public function actionDelimage()
	{
		$url = Yii::app()->params['site_path'].Yii::app()->request->getParam('url');
		$id = Yii::app()->request->getParam('id');
		@unlink($url);
		$this->redirect(array('update','id'=>$id));
	}
	public function actionDelMulti()
	{
		if(Yii::app()->request->isPostRequest){
			$arr_Id = Yii::app()->request->getParam('data');
			if(strpos($arr_Id,':')!==false){
				$arrid = explode(':', $arr_Id);
			}else{
				$arrid[]=$arr_Id;
			}
				
				foreach ($arrid as $id){
					if(is_numeric($id)){
						$model = $this->loadModel($id, 'News');
						if($model->images!=''){
							$images = unserialize($model->images);
							if(count($images)>0){
								foreach ($images as $value){
									@unlink(Yii::getPathOfAlias('rootPath').$value['url']);
								}
							}
						}
						$model->delete();
					}
				}
		}else 
			throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
	}
	public function actionIndex() {
		$dataProvider = new CActiveDataProvider('News');
		$this->render('index', array(
			'dataProvider' => $dataProvider,
		));
	}

	public function actionAdmin() {
		$dir = Yii::getPathOfAlias('application').'/helpers/js';
		$assets_path = Yii::app()->getAssetManager()->publish($dir);
		$cs = Yii::app()->getClientScript();
		$cs->registerScriptFile("{$assets_path}/form.js");
		
		$model = new News('search');
		$model->unsetAttributes();

		if (isset($_GET['News']))
			$model->attributes = $_GET['News'];
		$this->render('admin', array(
			'model' => $model,
		));
	}
	public function actionCrop()
	{
		if(isset($_POST['crop'])){
			CController::forward('/admin_news/news/cropnow');
		}else{
			$url = Yii::app()->request->getParam('url');
			$width = Yii::app()->request->getParam('width');
			$height = Yii::app()->request->getParam('height');
			$this->renderPartial('crop', array('url'=>$url, 'width'=>$width, 'height'=>$height));
		}
	}
	public function actionCropnow()
	{
		$jpeg_quality = 100;
	
		$src = Yii::app()->params['site_url'].Yii::app()->request->getParam('url');
		$x = Yii::app()->request->getParam('x');
		$y = Yii::app()->request->getParam('y');
		$w = Yii::app()->request->getParam('w');
		$h = Yii::app()->request->getParam('h');
		$targ_w = $w;
		$targ_h = $h;
		$parseurl = explode('.', $src);
		if(!count($parseurl)>0){
			echo 'not support this extension image';
			Yii::app()->end();
		}
		switch ($parseurl[count($parseurl)-1])
		{
			case 'png':
				$img_r = imagecreatefrompng($src);
				break;
			case 'gif':
				$img_r = imagecreatefromgif($src);
				break;
			default:
				$img_r = imagecreatefromjpeg($src);
				break;
		}
		
		$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
		imagecopyresampled($dst_r,$img_r,0,0,$x,$y,
		$targ_w,$targ_h,$w,$h);
		$newfile = dirname(Yii::app()->basePath).Yii::app()->request->getParam('url');
		switch ($parseurl[1])
		{
			case 'png':
				imagepng($dst_r,$newfile,$jpeg_quality);
				break;
			case 'gif':
				imagegif($dst_r,$newfile,$jpeg_quality);
				break;
			default:
				imagejpeg($dst_r,$newfile,$jpeg_quality);
				break;
		}
		echo '<script>window.parent.location.reload();</script>';
		Yii::app()->end();
	} 
}